/**
 * 
 */
package org.swing.utility.system.exception;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author lqnhu
 *
 */
public class ExceptionUtil {

	static public String getDetails(Exception err) {
		String causes = new String();

		if (err != null) {
			// message
			if (err.getMessage().compareToIgnoreCase("") != 0) {
				causes += "message: " + err.getMessage();
			}

			// causes
			List<String> causeList = new ArrayList<String>();
			getCauses(err.getCause(), causeList);
			if (!causeList.isEmpty()) {
				Collections.reverse(causeList);
				int rank = causeList.size();
				for (String msg : causeList) {
					causes += "\r\ncause " + rank + "/" + causeList.size()+ ": " + msg;
					rank--;
				}
			}

			// stackTrace
			StackTraceElement[] StackTraceElements = err.getStackTrace();
			if (StackTraceElements.length > 0) {
				causes += "\r\nStack Trace Elements:";
				for (StackTraceElement stackTraceElement : StackTraceElements) {
					causes += "\r\n" + stackTraceElement;
				}
			}
		}
		return causes;
	}

	static private void getCauses(Throwable cause, List<String> causeList) {
		if (cause != null && causeList != null) {
			String msg = cause.getMessage();
			if (msg != null && msg.trim().compareTo("") != 0) {
				causeList.add(msg);
			}
			if (cause.getCause() != null) {
				getCauses(cause.getCause(), causeList);
			}
		}
	}
}
